import React from 'react';
import {
  Badge, Button, Col, DatePicker, Drawer, Empty,
  Input, InputNumber, Layout, message, Modal,
  Popover, Radio, Row, Select, Switch,
  Tooltip, Tree, Upload,
} from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import { PageHeaderLayout, StandardTable, SearchForm, IconButton, PageCard } from '../../components';
import tools from '../../utils';
import { modalWidth, pageSize, apiUrl } from '../../../config';
import styles from './verify.css';
import Authorized from '../../utils/Authorized';
import moment from 'moment';

const residTypeData = require('../../assets/stureg_web/static/area.json');
const ethnicData = require('../../assets/stureg_web/static/ethnic.json');
const faceData = require('../../assets/stureg_web/static/face.json');
const types = require('../../assets/stureg_web/static/types.json');

const reqApi = 'verify';
const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const { Option } = Select;
const statusMapping = {};
const ethnicMapping = {};
const faceMapping = {};
const statusData = [
  ['1', '待审核'],
  ['2', '审核通过'],
  ['3', '审核拒绝'],
];
const situationMapping = {
  0: '应届',
  1: '往届',
};
const residTypeMapping = {};
residTypeData.map(item => {
  const { value, label, children } = item;
  residTypeMapping[value] = { label, children };
});
const residTypeMappingFull = {
  ...residTypeMapping,
  140402: { label: '潞州区' },
  140411: { label: '潞州区' },
  140421: { label: '上党区' },
  140424: { label: '屯留区' },
  140481: { label: '潞城区' },
};
let situationData = [];
const formItemLayout2 = {
  labelCol: { md: 6, xs: 7 },
  wrapperCol: { md: 18, xs: 17 },
};
let timer = 0;

const smallImageLimitSize = 140; // 缩略图限定尺寸(宽不能超过这个值)
const imageExceptionSize = 400; // 对于低分辨率的源图不做处理(不生成缩略图)

class page extends React.Component {
  state = {
    currentNavi: '',
    loadingNavi: false,
    loadingContent: false,

    visible: false,
    imageVisible: false, // 图片浏览框显隐
    visibleSend: false, // "发送订阅消息失败"表单显隐
    visibleTree: false, // "系部和专业"树显隐

    dialogLoadingAdjust: false,
    dialogLoadingCreate: false,

    dialogTitle: '',
    selectedRows: [],
    record: {},
    searchs: [],
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },

    userName: '',

    pictureUploading: false,
    examCardUploading: false,
    idCardFaceUploading: false,
    idCardBackUploading: false,
    currentFile: '', // 当前正在上传哪张图片

    autoRefresh: true, // 自动刷新

    formVisible: false, // 表单显隐
    formAction: 'create', // create新增, edit编辑
    formTitle: '后台代报',

    feedbackVisible: false, // "反馈信息"对话框显隐
    feedbackAction: 'allow', // allow审核通过, deny审核拒绝
    feedbackTitle: '',
    feedbackLabel: '反馈信息',
    feedbackLoading: false,
  };

  constructor(props) {
    super(props);
    statusData.map((item) => {
      const [key, value] = item;
      statusMapping[key] = value;
    });

    ethnicData.map((item) => {
      const { value, label } = item;
      ethnicMapping[value] = label;
    });

    faceData.map((item) => {
      const { value, label } = item;
      faceMapping[value] = label;
    });

    situationData = [];
    for (let value in situationMapping) {
      const label = situationMapping[value];
      situationData.push({ value, label });
    }

    if (timer) clearInterval(timer);

    const { state } = this;
    state.userName = sessionStorage.getItem('name');
  }

  componentDidMount() {
    this.funcGetNaviData();
  }

  componentWillUnmount() {
    window.onresize = null;
    if (timer) clearInterval(timer);
  }

  // 获取菜单数据
  funcGetNaviData = () => {
    this.setState({ loadingNavi: true });

    const { props } = this;
    props.dispatch({
      type: reqApi + '/listSpecial',
      payload: {
        currentPage: 1,
        pageSize: 1000,
      },
    }).then(() => {
      this.setState({ loadingNavi: false });
      this.funcGetListData();
      timer = setInterval(() => {
        const { autoRefresh } = this.state;
        if (autoRefresh) this.funcGetListData();
      }, 1000 * 30);
    });
  };

  // 获取列表数据
  funcGetListData = () => {
    this.setState({
      loadingContent: true,
      selectedRows: [],
    });

    const { state } = this;
    const { searchs, pagination } = state;
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    const newSearchs = [...searchs];

    if (state.currentNavi) {
      newSearchs.push({
        name: "specialId",
        value: state.currentNavi,
        searchType: "EQ",
        dataType: "STR",
      });
    }

    dispatch({
      type: reqApi + '/list',
      payload: {
        currentPage: current,
        pageSize,
        searchs: newSearchs,
      },
    }).then(() => {
      this.setState({ loadingContent: false });
    });
  };

  // 树实体
  treeBody = (data) => {
    const nodes = [];

    for (let i = 0; i < data.length; i += 1) {
      const item = data[i];
      const { key, title, children, selectable, pid } = item;
      const isSpec = pid > 0;

      nodes.push(
        <TreeNode
          key={key}
          selectable={selectable}
          title={isSpec ?
            (
              <div>
                <span>{title}</span>
                <Badge count={0} size='small' style={{ marginLeft: 4 }} />
              </div>
            ) :
            <div className={styles.treeNode}>{title}</div>
          }
        >
          {this.treeBody(children || [])}
        </TreeNode>,
      );
    }
    return nodes;
  };

  // 导航菜单
  naviMenu = () => {
    const { props } = this;
    const data = props[reqApi].dataSpecial;

    if (data.length) {
      return (
        <div
          style={{
            maxHeight: 'calc(100vh - ' + (window.isMobile ? 56 : 120) + 'px)',
            overflow: 'auto',
          }}
        >
          <Tree
            blockNode
            defaultExpandAll
            onSelect={(selectedKeys) => {
              this.setState({
                currentNavi: selectedKeys.length ? selectedKeys[0] : '',
                visibleTree: false,
              }, this.funcGetListData);
            }}
          >
            {this.treeBody(data)}
          </Tree>
        </div>
      );
    } else return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  };

  // 弹出表格
  funcOpenTable = (record) => {
    const { id, name, specialName } = record;

    this.setState({
      record,
      visible: true,
      dialogTitle: (
        <div>
          <Icon type='solution' style={{ fontSize: 16 }} />
          <span> {'“' + name + '”的报名信息'}</span>
        </div>
      ),
    });

    const { dispatch } = this.props;

    dispatch({
      type: reqApi + '/echo',
      payload: { action: 'edit', id },
    }).then(() => {
      const { props } = this;
      const { echoModel } = props[reqApi];
      this.setState({
        record: {
          specialName,
          ...echoModel,
        },
      });
    });
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const { id, name, specialId } = record;

    this.setState({
      record,
      formVisible: true,
      formAction: 'edit',
      formTitle: (
        <div>
          <Icon type='tool' style={{ fontSize: 16 }} />
          <span> {'调整“' + name + '”的报名信息'}</span>
        </div>
      ),
    }, () => {
      const values = { ...record };
      const { props } = this;
      const pid = props[reqApi].mappingSpecialPID[specialId];
      if (pid) values.pid = pid;
      props.form.setFieldsValue(values);
    });

    const { dispatch } = this.props;
    dispatch({
      type: reqApi + '/echo',
      payload: { action: 'edit', id },
    }).then(() => {
      const { props } = this;
      const { echoModel } = props[reqApi];

      if (echoModel.idCardNum.length === 18) {
        const a = echoModel.idCardNum.substr(6, 8);
        let b = a.substr(0, 4) + '-';
        b += a.substr(4, 2) + '-' + a.substr(6);
        echoModel.birthday = moment(b, 'YYYY-MM-DD');
      }
      echoModel.sex = echoModel.sex ? '1' : '0';
      echoModel.lodging = echoModel.lodging ? '1' : '0';
      echoModel.specialId += '';
      echoModel.type += '';
      echoModel.situation += '';
      echoModel.residType += '';
      echoModel.citytown = echoModel.citytown ? '1' : '0';

      props.form.setFieldsValue(echoModel);
    });
  };

  // 弹出反馈信息表单
  funcOpenFeedbackForm = (record, act) => {
    const { form } = this.props;
    form.resetFields();

    this.setState({
      feedbackVisible: true,
      feedbackAction: act,
      feedbackTitle: act === 'allow' ? (
        <div>
          <Icon type='check-square' style={{ fontSize: 16 }} />
          <span> {'通过“' + record.name + '”的报名'}</span>
        </div>
      ) : (
        <div>
          <Icon type='close-square' style={{ fontSize: 16 }} />
          <span> {'拒绝“' + record.name + '”的报名'}</span>
        </div>
      ),
      feedbackLabel: act === 'allow' ? '反馈信息' : '拒绝原因',
    }, () => {
      const { feedback } = window;
      if (act === 'allow' && feedback) {
        form.setFieldsValue({ feedback });
      }
    });
  };

  // 审核
  funcAudit = () => {
    const { form, dispatch } = this.props;
    const { state } = this;
    const act = state.feedbackAction;

    form.validateFields((error, values) => {
      if (error) return error;

      this.setState({ feedbackLoading: true });

      dispatch({
        type: reqApi + '/' + act,
        payload: {
          studentId: state.record.id,
          feedback: values.feedback,
        },
      }).then(() => {
        this.setState({ feedbackLoading: false });

        const { props } = this;
        const { success, errMsg } = props[reqApi];
        if (!success) return;

        this.setState({
          visible: false,
          feedbackVisible: false,
        });
        this.funcGetListData();
        if (errMsg) this.setState({ visibleSend: true });
        if (act === 'allow') window.feedback = values.feedback;
      });
    });
  };

  // 渲染状态
  renderStatus = (text, record) => {
    let result = '';
    switch (text) {
      case '1':
        result = (
          <Badge dot>
            <a onClick={() => this.funcOpenTable(record)}>
              {statusMapping[text]}
            </a>
          </Badge>
        );
        break;
      case '2':
        result = (
          <a onClick={() => this.funcOpenTable(record)}>
            <Icon
              type='check-circle'
              theme='twoTone'
              twoToneColor='limegreen'
              style={{ fontSize: 16 }}
            />
            <span style={{ color: 'limegreen' }}>
              {' ' + statusMapping[text]}
            </span>
          </a>
        );
        break;
      case '3':
        result = (
          <a onClick={() => this.funcOpenTable(record)}>
            <Icon
              type='minus-circle'
              style={{ fontSize: 16, color: 'darkgray' }}
            />
            <span style={{ color: 'darkgray' }}>
              {' ' + statusMapping[text]}
            </span>
          </a>
        );
    }
    return result;
  };

  // 表格列
  columns = () => [
    {
      title: '报名时间',
      dataIndex: 'signupTime',
      width: 100,
    },
    {
      title: '学生姓名',
      dataIndex: 'name',
      width: 110,
    },
    {
      title: '审核状态',
      dataIndex: 'status',
      width: 100,
      render: this.renderStatus,
    },
    {
      title: '报考专业',
      dataIndex: 'specialName',
      render: (text, record) => (
        <div>
          {record.status === '2' ? (
            <Authorized authority={() => tools.funcCheckValid(this.props, 'edit')}>
              <a key='icon' onClick={() => this.funcOpenForm(record)}>
                <Icon type='tool' className={styles.adjustIcon} title='调整信息' />
              </a>
            </Authorized>
          ) : null}
          <span>{text}</span>
        </div>
      ),
    },
    {
      title: '是否住校',
      dataIndex: 'lodging',
      width: 80,
      render: text => text === '1' ? '住校' : '不住校',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: '报名号',
      dataIndex: 'signup',
      width: 130,
    },
  ];

  // 查询列
  columnsSearch = [
    {
      title: '审核状态',
      dataIndex: 'status',
      type: 'select',
      sub: statusData,
    },
    {
      title: '学生姓名',
      dataIndex: 'name',
      type: 'text',
    },
  ];

  // 记录查询表单提交
  funcOnSubmitSearch = (searchs) => {
    const { state } = this;
    state.pagination.current = 1; // 进行查询操作则将页码归一
    this.setState({ searchs }, this.funcGetListData);
  };

  // 内容列表
  contentTable = () => {
    const { state, props } = this;
    const { data, total } = props[reqApi];

    return (
      <div>
        <SearchForm fields={this.columnsSearch} onSubmit={this.funcOnSubmitSearch} />

        <Row>
          <Col md={14} sm={24}>
            <Button.Group>
              {window.isMobile ? (
                <Button
                  type='primary'
                  style={{ marginBottom: 16 }}
                  onClick={() => this.setState({ visibleTree: true })}
                >选择专业</Button>
              ) : <div />}
              <Authorized authority={() => tools.funcCheckValid(props, 'create')}>
                <IconButton
                  text='新增'
                  type='default'
                  style={{ marginBottom: 16 }}
                  onClick={() => this.setState({
                    formVisible: true,
                    formAction: 'create',
                    formTitle: '后台代报',
                  })}
                />
              </Authorized>
              <Authorized authority={() => tools.funcCheckValid(props, 'delete')}>
                <IconButton
                  text='删除'
                  type='danger'
                  disabled={!state.selectedRows.length}
                  style={{ marginBottom: 16 }}
                  onClick={this.funcDelete}
                />
              </Authorized>
            </Button.Group>
          </Col>
          <Col md={10} sm={24} className={styles.extraText}>
            <label>
              <span>每30秒自动刷新：</span>
              <Switch
                checkedChildren='开启'
                unCheckedChildren='关闭'
                defaultChecked={true}
                onChange={(autoRefresh) => this.setState({ autoRefresh })}
              />
            </label>
          </Col>
        </Row>

        <StandardTable
          loading={state.loadingContent}
          columns={this.columns()}
          data={{
            list: data,
            pagination: { ...state.pagination, total },
          }}
          selectedRows={state.selectedRows}
          onSelectRow={(selectedRows) => this.setState({ selectedRows })}
          onChange={(pageParams) => {
            const { pagination } = this.state;
            pagination.current = pageParams.current;
            this.funcGetListData();
          }}
          scrollX={1280}
        />
      </div>
    );
  };

  // 删除
  funcDelete = () => {
    const { state } = this;
    let names = [], ids = [];
    for (let i = 0; i < state.selectedRows.length; i += 1) {
      const item = state.selectedRows[i];
      const { id, name } = item;
      names.push(name);
      ids.push(id);
    }

    Modal.confirm({
      title: "删除?",
      content: (
        <div>
          <div>你即将删除以下记录：</div>
          <div>{names + ''}</div>
          <div>请确认是否删除？</div>
        </div>
      ),
      okText: "是",
      okType: "danger",
      cancelText: "否",
      onOk: () => {
        this.setState({ loading: true });

        const { dispatch } = this.props;
        dispatch({
          type: reqApi + '/dele',
          payload: { ids: ids + '' },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData();
          else this.setState({ loading: false });
        });
      },
    });
  };

  // 保存学生报名信息
  funcSave = () => {
    const { formAction, record } = this.state;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      const data = { ...values };
      if (data.birthday)
        data.birthday = data.birthday.format('YYYY-MM-DD');
      if (formAction === 'edit')
        data.id = record.id;
      if (data.school === '其它学校')
        data.school = data.otherSchool || '其它学校';

      this.setState({ dialogLoadingCreate: true });

      dispatch({
        type: reqApi + '/' + formAction,
        payload: { data },
      }).then(() => {
        this.setState({ dialogLoadingCreate: false });
        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ formVisible: false });
          this.funcGetListData();
        }
      });
    });
  };

  // 包装路径为可访问的网络地址
  pathWrap = path => apiUrl() + '/upload/' + path + '?r=' + new Date().getTime();

  // 气泡框图片
  popoverImage = (src = '', maxHeight = 128) => {
    const src0 = src.replace('_sm.','.');

    return src ? (
      <Popover
        trigger='click'
        placement="left"
        content={(
          <img
            src={this.pathWrap(src0)}
            alt=''
            style={{ maxWidth: '80vw', maxHeight: '80vh' }}
          />
        )}
      >
        <img src={this.pathWrap(src0)} style={{ maxHeight }} alt='' />
      </Popover>
    ) : null;
  };

  // 检查手机号
  funcCheckPhone = (_, value) => {
    if (!value) {
      return Promise.reject('请输入手机号码');
    }

    const { form } = this.props;
    if (value === form.getFieldValue('phoneBackup')) {
      return Promise.reject('不能与家长电话相同');
    }

    return Promise.resolve();
  };

  // 检查家长电话
  funcCheckPhoneBackup = (_, value) => {
    const { form } = this.props;
    if (value === form.getFieldValue('phone')) {
      return Promise.reject('不能与手机号相同');
    }

    return Promise.resolve();
  };

  // 检查图片是否有效
  funcCheckFile = (file) => {
    const size0 = 5;
    const size = 1024 * 1024 * size0;

    let isOk = true;
    if (file.size > size) {
      message.error(file.name + " 不能超过 " + size0 + "MB");
      isOk = false;
    }

    if (isOk) {
      const reader = new FileReader();
      reader.onload = (e) => this.funcDisposeFile(e, file, this.funcUploadFile);
      reader.readAsDataURL(file);
    } else {
      const { state } = this;
      state[state.currentFile + 'Uploading'] = false;
      this.setState({});
    }
    return false;
  };

  // 在源图基础上生成缩略图
  funcDisposeFile = (e, file, callback) => {
    const fileExt = file.name.substr(file.name.lastIndexOf(".") + 1);
    const b64 = e.target.result;
    const img = new Image();
    img.onload = () => {
      // 例外处理, 低分辨率的源图则没必要生成缩略图了
      if (img.width <= imageExceptionSize) {
        callback(b64.split(",")[1], fileExt);
        return;
      }

      // 生成缩略图(供列表页面使用，节省流量)
      // 缩略图宽度固定是"smallImageLimitSize"的值
      const ratio = img.width / img.height;
      img.width = smallImageLimitSize;
      img.height = Math.round(smallImageLimitSize / ratio);

      const canvas = document.createElement("canvas");
      const ct = canvas.getContext("2d");
      canvas.width = img.width;
      canvas.height = img.height;
      ct.drawImage(img, 0, 0, img.width, img.height);
      const b64sm = canvas.toDataURL(file.type);

      callback(b64.split(",")[1], fileExt, b64sm.split(",")[1]);
    };
    img.src = b64;
  };

  // 开始上传图片
  funcUploadFile = (b64, imgType, b64sm) => {
    const { currentFile } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: reqApi + '/upload',
      payload: {
        b64,
        b64sm,
        imgType,
        fieldName: currentFile,
      },
    }).then(() => {
      const { state, props } = this;
      state[currentFile + 'Uploading'] = false;
      this.setState({});

      const { success, uploadUrl } = props[reqApi];
      if (success) {
        const values = {};
        values[currentFile] = uploadUrl;
        props.form.setFieldsValue(values);
      }
    });
  };

  render() {
    const { state, props } = this;
    const { record } = state;
    const { form } = props;
    const { getFieldDecorator } = form;
    const { errMsg } = props[reqApi];
    const specSelectData = props[reqApi].specData[form.getFieldValue('pid')] || [];
    let typeSelectData = [];
    const specialId = form.getFieldValue('specialId');
    if (specialId) {
      for (let i = 0; i < specSelectData.length; i += 1) {
        const item = specSelectData[i];
        const { id, types } = item;
        if (id === specialId) {
          try {
            typeSelectData = JSON.parse(types);
          } catch(e) {
            typeSelectData = [];
          }
        }
      }
    }
    const drawerFooter = record.status === 1 ? [
      <IconButton
        key='close'
        text='关闭'
        type='default'
        onClick={() => {
          this.setState({
            visible: false,
            feedbackVisible: false,
          });
        }}
      />,
      <IconButton
        key='deny'
        text={(window.isMobile ? '' : '审核') + '拒绝'}
        type='danger'
        icon='close'
        style={{ margin: '0 8px' }}
        onClick={() => this.funcOpenFeedbackForm(record, 'deny')}
      />,
      <IconButton
        key='allow'
        text={(window.isMobile ? '' : '审核') + '通过'}
        icon='check'
        onClick={() => this.funcOpenFeedbackForm(record, 'allow')}
      />,
    ] : (
      <IconButton
        text='关闭'
        onClick={() => {
          this.setState({
            visible: false,
            feedbackVisible: false,
          });
        }}
      />
    );
    let drawerBodyPadding = 24;
    if (window.isPad) drawerBodyPadding = 16;
    if (window.isMobile) drawerBodyPadding = 0;

    const { status } = record;
    let st = statusMapping[status];
    if (status === 3) {
      st += '：' + record.feedback;
    } else if (status === 2) {
      st += '，审核员：' + record.auditAdminName;
    }

    return (
      <PageHeaderLayout title={props.route.name}>
        <PageCard
          bodyStyle={{
            padding: 0,
            overflow: 'hidden',
          }}
          children={(
            <Layout>
              {window.isMobile ? null : (
                <Sider
                  theme='light'
                  width={240}
                  style={{ borderRight: '1px solid gainsboro' }}
                >
                  {this.naviMenu()}
                </Sider>
              )}
              <Content
                style={{
                  padding: '16px 8px 0 8px',
                  backgroundColor: 'white',
                }}
              >
                {this.contentTable()}
              </Content>
            </Layout>
          )}
        />

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title={state.formTitle}
          visible={state.formVisible}
          onClose={() => this.setState({ formVisible: false })}
          bodyStyle={{ paddingBottom: 0 }}
          footerStyle={{ textAlign: 'right' }}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ formVisible: false })}
            />,
            <IconButton
              key='save'
              text='保存'
              loading={state.dialogLoadingCreate}
              style={{ marginLeft: 8 }}
              onClick={this.funcSave}
            />,
          ]}
        >
          {state.formVisible ? (
            <Form>
              <Row gutter={{ md: 24, sm: 8 }}>
                <Col md={12} sm={24}>
                  <Form.Item label='姓名' {...formItemLayout2}>
                    {getFieldDecorator('name', {
                      rules: [{ required: true, message: '请输入姓名' }],
                    })(<Input autoFocus maxLength={10} />)}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='性别' {...formItemLayout2}>
                    {getFieldDecorator('sex', { initialValue: '1' })(
                      <Radio.Group disabled>
                        <Radio value='1'>男</Radio>
                        <Radio value='0'>女</Radio>
                      </Radio.Group>
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="学生类别" {...formItemLayout2}>
                    {getFieldDecorator("situation", { initialValue: '0' })(
                      <Radio.Group buttonStyle="solid">
                        {situationData.map((item) => {
                          const { value, label } = item;
                          return <Radio.Button key={value} value={value}>{label}</Radio.Button>;
                        })}
                      </Radio.Group>
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="所在居住地" {...formItemLayout2}>
                    {getFieldDecorator("residType", { initialValue: '140403' })(
                      <Select
                        onChange={value =>
                          form.setFieldsValue({school: value === '0' ? '其它学校' : ''})
                        }
                      >
                        {residTypeData.map(item => {
                          const { value, label } = item;
                          return <Option key={value} value={value}>{label}</Option>;
                        })}
                      </Select>
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='毕业学校' {...formItemLayout2}>
                    {getFieldDecorator('school', {
                      rules: [{ required: true, message: '请选择毕业学校' }],
                    })(
                      <Select>
                        {form.getFieldValue('residType') !== '0' ?
                          (residTypeMapping[form.getFieldValue('residType')].children + ',其它学校')
                            .split(',').map(school =>
                            <Option key={school} value={school}>{school}</Option>
                          ) : <Option key='其它学校' value='其它学校'>其它学校</Option>
                        }
                      </Select>
                    )}
                  </Form.Item>
                </Col>

                {form.getFieldValue('school') === '其它学校' ? (
                  <Col md={12} sm={24}>
                    <Form.Item label='其它学校' {...formItemLayout2}>
                      {getFieldDecorator('otherSchool')(<Input maxLength={10} />)}
                    </Form.Item>
                  </Col>
                ) : null}

                <Col md={12} sm={24}>
                  <Form.Item label='家庭住址' {...formItemLayout2}>
                    {getFieldDecorator('address', {
                      rules: [{ required: true, message: '请输入家庭住址' }],
                    })(<Input maxLength={50} />)}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="手机号码" {...formItemLayout2}>
                    {getFieldDecorator("phone", {
                      rules: [{ required: true, validator: this.funcCheckPhone }],
                    })(<InputNumber min={0} max={19999999999} style={{ width: '100%' }} />)}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="家长电话" {...formItemLayout2}>
                    {getFieldDecorator("phoneBackup", {
                      rules: [{ required: false, validator: this.funcCheckPhoneBackup }],
                    })(
                      <InputNumber min={0} max={19999999999} style={{ width: '100%' }} />
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='身份证号' {...formItemLayout2}>
                    {getFieldDecorator('idCardNum', {
                      rules: [{ required: true, message: '请输入身份证号' }],
                    })(
                      <Input
                        maxLength={18}
                        onChange={e => {
                          const { value } = e.target;
                          if (value.length < 14) return;

                          const date = value.substr(6, 8);
                          const birthday = moment(date, 'YYYYMMDD');
                          form.setFieldsValue({ birthday });

                          if (value.length < 17) return;

                          const sex = value[16] % 2 + '';
                          form.setFieldsValue({ sex });
                        }}
                      />
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='准考证号' {...formItemLayout2}>
                    {getFieldDecorator("examCardNum")(
                      <InputNumber min={0} maxLength={9} style={{ width: '100%' }} />
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='报名号' {...formItemLayout2}>
                    {getFieldDecorator("signup")(
                      <InputNumber min={0} maxLength={12} style={{ width: '100%' }} />
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='中考成绩' {...formItemLayout2}>
                    {getFieldDecorator("sum")(
                      <InputNumber min={0} max={1000} step={10} style={{ width: '100%' }} />
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='系部' {...formItemLayout2}>
                    {getFieldDecorator('pid')(
                      <Select onChange={() => form.setFieldsValue({ specialId: '' })}>
                        {props[reqApi].sysData.map((item) => {
                          const { id, name } = item;
                          return <Option key={id} value={id}>{name}</Option>;
                        })}
                      </Select>
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="报考专业" {...formItemLayout2}>
                    {getFieldDecorator("specialId", {
                      rules: [{ required: true, message: '请选择报考专业' }],
                    })(
                      <Select>
                        {specSelectData.map((item) => {
                          const { id, name } = item;
                          return <Option key={id} value={id}>{name}</Option>;
                        })}
                      </Select>
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='报考类别' {...formItemLayout2}>
                    {getFieldDecorator('type', {
                      rules: [{ required: true, message: '请选择报考类别' }],
                    })(
                      <Radio.Group buttonStyle="solid">
                        {typeSelectData.map((type) => {
                          return (
                            <Radio.Button key={type + ''} value={type + ''}>
                              {types[type]}
                            </Radio.Button>
                          );
                        })}
                      </Radio.Group>
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="是否住校" {...formItemLayout2}>
                    {getFieldDecorator("lodging", { initialValue: '1' })(
                      <Radio.Group buttonStyle="solid">
                        <Radio.Button value='1'>住校</Radio.Button>
                        <Radio.Button value='0'>不住校</Radio.Button>
                      </Radio.Group>
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='民族' {...formItemLayout2}>
                    {getFieldDecorator('ethnic')(
                      <Select>
                        {ethnicData.map((item) => {
                          const { value, label } = item;
                          return <Option key={value} value={value}>{label}</Option>;
                        })}
                      </Select>
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="特长" {...formItemLayout2}>
                    {getFieldDecorator("speciality")(<Input maxLength={255} />)}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="免冠证件照" {...formItemLayout2}>
                    {getFieldDecorator("picture")(
                      <Input
                        disabled={state.pictureUploading}
                        suffix={
                          state.pictureUploading ? (
                            <Icon type="loading" />
                          ) : (
                            <Upload
                              accept="image/*"
                              showUploadList={false}
                              beforeUpload={(file) => {
                                if (state.pictureUploading) return false;
                                this.setState({
                                  pictureUploading: true,
                                  currentFile: 'picture',
                                }, () => this.funcCheckFile(file));
                              }}
                            >
                              <Tooltip title="选择图片">
                                <Icon type="upload" />
                              </Tooltip>
                            </Upload>
                          )
                        }
                      />,
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="准考证照片" {...formItemLayout2}>
                    {getFieldDecorator("examCard")(
                      <Input
                        disabled={state.examCardUploading}
                        suffix={
                          state.examCardUploading ? (
                            <Icon type="loading" />
                          ) : (
                            <Upload
                              accept="image/*"
                              showUploadList={false}
                              beforeUpload={(file) => {
                                if (state.examCardUploading) return false;
                                this.setState({
                                  examCardUploading: true,
                                  currentFile: 'examCard',
                                }, () => this.funcCheckFile(file));
                              }}
                            >
                              <Tooltip title="选择图片">
                                <Icon type="upload" />
                              </Tooltip>
                            </Upload>
                          )
                        }
                      />,
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="身份证正面" {...formItemLayout2}>
                    {getFieldDecorator("idCardFace")(
                      <Input
                        disabled={state.idCardFaceUploading}
                        suffix={
                          state.idCardFaceUploading ? (
                            <Icon type="loading" />
                          ) : (
                            <Upload
                              accept="image/*"
                              showUploadList={false}
                              beforeUpload={(file) => {
                                if (state.idCardFaceUploading) return false;
                                this.setState({
                                  idCardFaceUploading: true,
                                  currentFile: 'idCardFace',
                                }, () => this.funcCheckFile(file));
                              }}
                            >
                              <Tooltip title="选择图片">
                                <Icon type="upload" />
                              </Tooltip>
                            </Upload>
                          )
                        }
                      />,
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="身份证背面" {...formItemLayout2}>
                    {getFieldDecorator("idCardBack")(
                      <Input
                        disabled={state.idCardBackUploading}
                        suffix={
                          state.idCardBackUploading ? (
                            <Icon type="loading" />
                          ) : (
                            <Upload
                              accept="image/*"
                              showUploadList={false}
                              beforeUpload={(file) => {
                                if (state.idCardBackUploading) return false;
                                this.setState({
                                  idCardBackUploading: true,
                                  currentFile: 'idCardBack',
                                }, () => this.funcCheckFile(file));
                              }}
                            >
                              <Tooltip title="选择图片">
                                <Icon type="upload" />
                              </Tooltip>
                            </Upload>
                          )
                        }
                      />,
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label='推荐教师' {...formItemLayout2}>
                    {getFieldDecorator("recommend", { initialValue: state.userName })(
                      <Input maxLength={10} />
                    )}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="备注" {...formItemLayout2}>
                    {getFieldDecorator("remark")(
                      <Input maxLength={255} />
                    )}
                  </Form.Item>
                </Col>

                <Col span={0}>
                  <Form.Item label="出生日期" {...formItemLayout2}>
                    {getFieldDecorator('birthday', {
                      initialValue: moment(),
                    })(
                      <DatePicker
                        format='YYYY-MM-DD'
                        style={{ width: '100%' }}
                        disabledDate={(now) => {
                          return now < moment('2000-01-01', 'YYYY-MM-DD') ||
                            now > moment().startOf('day');
                        }}
                      />
                    )}
                  </Form.Item>
                </Col>

              </Row>
            </Form>
          ) : null}
        </Drawer>

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title={state.dialogTitle}
          visible={state.visible}
          onClose={() => {
            this.setState({
              visible: false,
              feedbackVisible: false,
            });
          }}
          bodyStyle={{ padding: drawerBodyPadding }}
          footerStyle={{ textAlign: 'right' }}
          footer={drawerFooter}
        >
          {window.isMobile ? null : (
            <div className={styles.title}>
              长治市职业高级中学招生登记表
            </div>
          )}
          <table className={styles.header}>
            <tbody>
            <tr>
              <td>
                <label>报名号</label>
                <span>{record.signup}</span>
              </td>
              <td align='right'>
                <label>准考证号</label>
                <span>{record.examCardNum}</span>
              </td>
            </tr>
            </tbody>
          </table>
          <table className={styles.table}>
            <tbody>
            <tr>
              <th>姓名</th><td>{record.name}</td>
              <th>性别</th><td>{record.sex ? '男' : '女'}</td>
              <td rowSpan={3}>
                {this.popoverImage(record.picture, 190)}
              </td>
            </tr>
            <tr>
              <th>出生日期</th><td>{record.birthday ? record.birthday.substr(0, 10) : ''}</td>
              <th>民族</th><td>{record.ethnic ? ethnicMapping[record.ethnic] : ''}</td>
            </tr>
            <tr>
              <th>学生类别</th><td>{situationMapping[record.situation]}</td>
              <th>电话</th>
              <td>
                <div>{record.phone}</div>
                <div>{record.phoneBackup}</div>
              </td>
            </tr>
            <tr>
              <th>中考成绩</th><td>{record.sum}</td>
              <th>身份证号</th><td colSpan={2}>{record.idCardNum}</td>
            </tr>
            <tr>
              <th>毕业学校</th><td>{record.school}</td>
              <th>家庭住址</th><td colSpan={2}>{record.address}</td>
            </tr>
            <tr>
              <th style={{ height: 128 }}>准考证</th>
              <td>
                {this.popoverImage(record.examCard)}
              </td>
              <th>身份证</th>
              <td>
                {this.popoverImage(record.idCardFace)}
              </td>
              <td>
                {this.popoverImage(record.idCardBack)}
              </td>
            </tr>
            <tr>
              <th colSpan={3}>报考专业</th><th>是否住校</th><th>备注</th>
            </tr>
            <tr>
              <td colSpan={3}>{record.specialName}</td>
              <td>{record.lodging ? '住校' : '不住校'}</td>
              <td>{record.remark}</td>
            </tr>
            <tr>
              <th colSpan={3}>所在居住地</th>
              <th colSpan={2}>特长</th>
            </tr>
            <tr>
              <td colSpan={3}>
                {residTypeMappingFull[record.residType] ?
                  residTypeMappingFull[record.residType].label : '外地'}
              </td>
              <td colSpan={2}>{record.speciality}</td>
            </tr>
            <tr>
              <th>推荐老师</th><td>{record.recommend}</td>
              <th>审核情况</th><td colSpan={3}>{st}</td>
            </tr>
            </tbody>
          </table>
        </Drawer>

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title='选择专业'
          visible={state.visibleTree}
          onClose={() => this.setState({ visibleTree: false })}
          bodyStyle={{ padding: 0 }}
        >
          {this.naviMenu()}
        </Drawer>

        <Modal
          width={modalWidth}
          title={state.feedbackTitle}
          visible={state.feedbackVisible}
          bodyStyle={{ paddingBottom: 0 }}
          onOk={this.funcAudit}
          onCancel={() => this.setState({ feedbackVisible: false })}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ feedbackVisible: false })}
            />,
            <IconButton
              key='ok'
              text='确定'
              loading={state.feedbackLoading}
              onClick={this.funcAudit}
            />
          ]}
        >
          {state.feedbackVisible ? (
            <Form>
              <Form.Item
                label={state.feedbackLabel + ' (限20个字以内)'}
                labelCol={{ span: 24 }}
              >
                {getFieldDecorator('feedback', {
                  rules: [{
                    required: true,
                    message: state.feedbackLabel + '不能为空',
                  }],
                })(
                  <Input.TextArea
                    autoFocus
                    maxLength={20}
                    rows={3}
                    showCount
                  />
                )}
              </Form.Item>
            </Form>
          ) : null}
        </Modal>

        <Modal
          width={modalWidth}
          title={(
            <div>
              <Icon type='warning' style={{ fontSize: 16 }} />
              <span> 发送订阅消息发生错误</span>
            </div>
          )}
          visible={state.visibleSend}
          onOk={() => this.setState({ visibleSend: false })}
          onCancel={() => this.setState({ visibleSend: false })}
          footer={(
            <IconButton
              text='关闭'
              onClick={() => this.setState({ visibleSend: false })}
            />
          )}
        >
          <p>{errMsg}</p>
          <p>为了能够及时反馈给学生信息，建议进行电话联系：</p>
          <p>{record.name + ' ' + record.phone + ' ' + record.phoneBackup}</p>
        </Modal>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ verify, menu }) => ({ verify, menu }))(page2);
